<template>
  <div>
    <div class="pic" v-if="imageUrl">
      <el-image style="width: 140px; height: 140px" :src="pic" fit="contain" />
    </div>
    <el-upload
      ref="upload"
      class="avatar-uploader"
      action="/api/upload"
      name="file"
      accept="image/png, image/jpeg"
      show-file-list="false"
      :on-success="uploadSuccess"
      :before-upload="beforeUpload"
      :on-remove="removePic"
    >
      <el-icon v-if="!imageUrl" class="avatar-uploader-icon"><Plus /></el-icon>
      <template #tip v-if="!imageUrl">
        <div class="el-upload__tip text-red">只能上传一张jpeg或png图片，且不超过1M</div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
import { ref, defineEmits, } from "vue";
import { ElMessage } from 'element-plus'
// 上传图片
const pic = ref("");
const props = defineProps<{
 cover?:string
}>()
pic.value = props.cover!
const imageUrl = ref<boolean>(false);

// 图片上传成功时
const emit = defineEmits<{
  (e: 'getPic' , pic:any ):void
}>()

const uploadSuccess = (res: { data: { url: string } }) => {
  imageUrl.value = true;
  pic.value = res.data.url;
  emit('getPic', pic)
};

// 移除已经上传的图片
const removePic = () => {
  pic.value = "";
  imageUrl.value = false;
};
// 上传前对上传的图片格式进行验证
const picArr=['image/png','image/jpeg']
const beforeUpload = (file: any) => {
  if (file.size > 1024 * 1024) {
    ElMessage({
      message: "图片体积不能超过1M",
      type: "error",
    })
    return false
  }else if(picArr.indexOf(file.type) === -1){
    ElMessage({
      message: "图片类型必须是jpeg/png格式",
      type: "error",
    })
    return false
  }
  return true
};
</script>

<style scoped lang="scss">
// 上传图片的样式
.pic {
  height: 140px;
  width: 140px;
  background-color: #fff;
}
:deep .el-upload {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
:deep .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  text-align: center;
  background-color: #fff;
}

:deep .avatar-uploader {
  position: relative;
}
:deep .el-upload-list__item {
  position: absolute;
  top: -42px;
  left: 0;
}
</style>
